import { action, computed, observable } from "mobx";
import { WeaForm, WeaTableNew } from 'comsMobx'
import APPAPI from '../../apis/app';
import API from '../../apis/data';
import TASKAPI from '../../apis/task';
import { fillinTypes } from "../../constants/app";
import ListAction from './listAction';
import { ExcelPageViewStore } from '../../stores/task';
import { WeaLocaleProvider } from "ecCom";
import DataExcelStore from "../dataExcel/DataExcelStore";

const getLabel = WeaLocaleProvider.getLabel;


const { TableStore } = WeaTableNew;
export default class DataStore {
    @observable loading = false;
    @observable searchValue = '';
    @observable subTitle = '';
    @observable title = '';
    @observable fillinType = '';
    @observable selectedTab = 'data';
    @observable leftDatas = [];
    @observable selectedTask = '';
    @observable appid = '';

    // list
    @observable tableStore = new TableStore();
    @observable customSearchMap = {};
    @observable forms = [];
    @observable selectedForm = '';
    @observable noData = false;
    @observable currentTableName = '主表';
    @observable currentTable = '0';
    @observable downloadPopverVisible = false;

    // path
    @observable pathNode;
    @observable noPath = false;

    // analysis
    @observable analysisLoaded = false;

    @observable conditionVisible = false;
    @observable isData = true;
    @observable isMain = true;
    @observable searchType = ['advanced'];
    @observable showAdvance = true;
    @observable conditionForm = new WeaForm();

    @observable isRight = false;
    @observable loadingPage = true;
    @observable hide = false;
    @observable slideStore = new ExcelPageViewStore();
    @observable sessionkey = '';
    @observable excelStore;
    @observable hasFields = '0';
    @observable fieldOptions = [];
    @observable relatedLayout;
    @observable detailData = {
        comps: [],
        sys: {}
    };
    @observable appData = {};

    constructor() {
        ListAction(this);

        this.excelStore = new DataExcelStore(this);
        this.setConditionVisible = this.setConditionVisible.bind(this);
        this.search = this.search.bind(this);
        this.quickSearch = this.quickSearch.bind(this);
        this.changeQuickSearchValue = this.changeQuickSearchValue.bind(this);
        this.clearCondition = this.clearCondition.bind(this);
    }

    @computed
    get tabs() {
        if (this.fillinType === fillinTypes.MULTI) {
            return [{
                key: 'data',
                title: getLabel(563, '数据')
            }, {
                key: 'path',
                title: getLabel(18499, '路径')
            }, {
                key: 'analysis',
                title: getLabel('502851', '分析')
            }];
        } else if (this.fillinType === fillinTypes.FREE) {
            return [{
                key: 'data',
                title: getLabel(563, '数据')
            }, {
                key: 'analysis',
                title: getLabel('502851', '分析')
            }];
        }
        return [];
    }
    @computed get apps() {
        return this.leftDatas.filter(d => d.name.toLowerCase().indexOf(this.searchValue.toLowerCase()) > -1);
    }

    @computed get quickSearchValue() {
        if (this.conditionForm.isFormInit && this.conditionForm.has('TBR')) {
            return this.conditionForm.$('TBR').values();
        }
        return '';
    }

    @action onChangeTab = (selectedTab) => {
        if (selectedTab === 'data') {
            this.isData = true;

            //this.searchType = ['advanced'];
            // if (this.isData && this.isMain) {
            //     this.searchType = ['advanced'];
            // } else {
            //     this.searchType = [];
            // }

        } else {
            this.isData = false;
            this.searchType = [];
        }

        this.selectedTab = selectedTab;
        this[`init${selectedTab}`](1);
    }

    @action init = (params) => {
        this.loading = true;
        this.appid = params.appid;
        this.params = params;
        TASKAPI.showDetail({ appid: params.appid }).then(data => {
            this.loadingPage = false;
            this.isRight = data.isShowDetail;
            if (this.isRight) {
                APPAPI.info(params.appid).then(data => {
                    this.appData = data;
                    // this.conditions = this.getConditions(data.fillinType, this.appid);
                    // this.conditionForm.initFormFields(this.conditions);
                    this.setApp(data);
                });
                API.taskList(params.appid).then(this.setTaskList);
            }
        });

    }
    @action
    initTable = () => {
        API.data({
            //type: this.selectedTab,
            data: 1,
            appid: this.appid,
            quickSearchValue: this.quickSearchValue,
            //...this.conditionForm.getFormParams()
        }).then(this.fetchDatas);
    }


    @action
    filterTable = (filterMap) => {
        API.data({
            data: 1,
            appid: this.appid,
            quickSearchValue: this.quickSearchValue,
            filterMap: JSON.stringify(filterMap),
            ...this.conditionForm.getFormParams()
        }).then(this.fetchDatas);
    }

    @action
    fetchDatas = (data) => {

        this.tableStore.getDatas(data.datas);
    }
    @action setTaskList = (leftDatas) => {
        this.leftDatas = leftDatas;
    }
    @action changeSelectedTask = (taskid) => {
        this.selectedTask = taskid;

        const [selectedTask] = this.leftDatas.slice().filter(d => d.id === this.selectedTask);
        this.subTitle = selectedTask ? `:${selectedTask.name}` : '';
        if (this.conditionForm.isFormInit) {
            this.conditionForm.updateFields({
                "taskid": {
                    value: taskid,
                    valueSpan: selectedTask.name,
                    valueObj: [{ id: taskid, name: selectedTask.name }]
                }

            });
        }
        this[`init${this.selectedTab}`](1);
    }

    @action updateConditions = (conditions) => {
        console.log(conditions)
        if (!conditions) {
            conditions = [];
        }
        if (conditions.length == 0) {

            this.searchType = [];
        } else {
            this.searchType = ['advanced'];
        }
        this.conditions = conditions;
        this.conditionForm = new WeaForm();
        this.conditionForm.initFormFields(conditions);


    }

    @action initpath = () => {
        this.loading = true;
        if (this.selectedTask) {
            API.path(this.selectedTask).then(this.setPath);
        } else {
            this.noPath = true;
        }
        this.loading = false;
    }
    @action setPath = (node) => {
        this.pathNode = node;
        this.noPath = false;
    }
    @action initanalysis = () => {
        this.loading = true;
        API.analysis(this.appid).then(this.setAnalysis);
    }
    @action setAnalysis = (boardId) => {
        this.loading = false;
        this.boardId = boardId;
    }
    @action setAnalysisLoaded = (bool) => {
        this.analysisLoaded = bool;
    }

    @action changeQuickSearchValue(value) {
        if (this.conditionForm.isFormInit) {
            this.conditionForm.updateFields({
                TBR: { value }
            });
        }
    }
    @action quickSearch() {
        this.initTable();
    }


    @action search() {
        //this.initTable();
        this.excelStore.onFilter();
        this.setConditionVisible(false);
        
    }

    @action clearCondition() {
        this.conditionForm.resetForm()
    }

    @action getConditions(fillinType, appid) {
        return [{
            title: getLabel('502852', '常用条件'),
            defaultshow: true,
            items: [{
                colSpan: 2,
                conditionType: "BROWSER",
                domkey: [
                    "taskid"
                ],
                fieldcol: 12,
                label: getLabel('502853', '任务名称'),
                labelcol: 6,
                value: "",
                viewAttr: 2,
                hide: fillinType === fillinTypes.FREE,
                browserConditionParam: {
                    completeParams: {},
                    conditionDataParams: {},
                    dataParams: { "appid": appid },
                    completeParams: { "appid": appid },
                    destDataParams: {},
                    hasAddBtn: false,
                    hasAdvanceSerach: true,
                    idSeparator: ",",
                    isAutoComplete: 1,
                    isDetail: 0,
                    isMultCheckbox: false,
                    isSingle: false,
                    pageSize: 10,
                    quickSearchName: "",
                    replaceDatas: [],
                    title: getLabel('502853', '任务名称'),
                    type: "edcTask",
                    icon: "icon-coms02-Data-center",
                    viewAttr: 2
                },
            }, {
                colSpan: 2,
                conditionType: "BROWSER",
                domkey: [
                    "creator"
                ],
                fieldcol: 12,
                label: getLabel('502854', '提交人'),
                labelcol: 6,
                value: "",
                viewAttr: 2,
                browserConditionParam: {
                    completeParams: {},
                    conditionDataParams: {},
                    dataParams: {},
                    destDataParams: {},
                    hasAddBtn: false,
                    hasAdvanceSerach: true,
                    idSeparator: ",",
                    isAutoComplete: 1,
                    isDetail: 0,
                    isMultCheckbox: false,
                    isSingle: false,
                    pageSize: 10,
                    quickSearchName: "",
                    replaceDatas: [],
                    title: getLabel(502300, "人力资源"),
                    type: "17",
                    viewAttr: 2
                },
            }, {
                colSpan: 2,
                conditionType: "INPUT",
                domkey: [
                    "wxNickname"
                ],
                fieldcol: 12,
                label: getLabel('502855', '微信用户名'),
                labelcol: 6,
                value: "",
                viewAttr: 2,
                hide: fillinType !== fillinTypes.FREE
            }, {
                colSpan: 2,
                fieldcol: 12,
                labelcol: 6,
                conditionType: "SELECT_LINKAGE",
                selectLinkageDatas: {
                    "6": {
                        conditionType: "RANGEPICKER",
                        domkey: [
                            "start",
                            "end"
                        ]
                    }
                },
                options: [{
                    key: "0",
                    showname: getLabel(332, "全部"),
                    selected: true
                }, {
                    key: "1",
                    showname: getLabel('502856', '今天')
                }, {
                    key: "2",
                    showname: getLabel('502857', '本周')
                }, {
                    key: "3",
                    showname: getLabel('502858', '本月')
                }, {
                    key: "5",
                    showname: getLabel('502859', '本年')
                }, {
                    key: "7",
                    showname: getLabel('502860', '上个月')
                }, {
                    key: "8",
                    showname: getLabel('502861', '上一年')
                }, {
                    key: "6",
                    showname: getLabel('502862', '指定日期范围')
                }
                ],
                domkey: [
                    "createDateType",
                    "createDate"
                ],
                label: getLabel('505955', '提交时间'),
                viewAttr: 3
            }]
        }]
    }

    @action setConditionVisible(visible) {
        this.conditionVisible = visible;
        this.excelStore.hideFilter()
    }

    @action setLeftSearchValue = (value) => {
        this.searchValue = value;
    }

    @action changeHide = (bool) => {
        this.hide = bool;
    }
    @action onCollapse = () => {
        this.excelStore.refreshExcel();
    }

    @action
    fetchDetailData = (dataid, formid) => {
        API.detailData(dataid, formid).then(res => {
            this.detailData = res;
        });
    }

    @action
    showContent = (bool) => {
        this.downloadPopverVisible = bool;
        if(bool) {

            this.excelStore.filterVisible = false;
        }
    }
}